package channelService

import (
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelAPI"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"reflect"
	"sync"
)

type reportService struct {
	mutex sync.RWMutex
	datas []*commRedisRpc.ChannelRespondVO
}

func (e *reportService) popAll() ([]*commRedisRpc.ChannelRespondVO, error) {
	return e.remove(), nil
}

func (e *reportService) push(channelName string, data interface{}) {
	if data == nil {
		return
	}

	respondVO := commRedisRpc.Type.ChannelRespondVO.New()
	respondVO.Uuid = ""
	respondVO.Type = commEnv.Service.ModelName
	respondVO.Name = channelName

	if reflect.TypeOf(data).Kind() == reflect.String {
		respondVO.Recv = data
	}
	if reflect.TypeOf(data).Kind() == reflect.Slice && reflect.TypeOf(data).Elem().Kind() == reflect.Uint8 {
		respondVO.Recv = Hex.EncodeToString(data.([]byte))
	}

	e.append(respondVO)

	// 向API框架发出信号：有数据需要上报了
	channelAPI.Service.NotifyReport()
}

func (e *reportService) append(respondVO *commRedisRpc.ChannelRespondVO) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	e.datas = append(e.datas, respondVO)
}

func (e *reportService) remove() []*commRedisRpc.ChannelRespondVO {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	datas := e.datas
	e.datas = make([]*commRedisRpc.ChannelRespondVO, 0)
	return datas
}
